<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>按键支持多音轨控制音频播放</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .highlighted {
            background-color: yellow;
        }
    </style>
</head>

<body>

    <div class="audio-item" data-src="56.mp3">音频 0</div>
    <div class="audio-item" data-src="57.mp3">音频 1</div>
    <div class="audio-item" data-src="58.mp3">音频 2</div>
    <div class="audio-item" data-src="59.mp3">音频 3</div>
    <div class="audio-item" data-src="60.mp3">音频 4</div>

    <script>
        //需要修改两个点
        //1.键盘支持多键高亮
        //2.支持多音轨播放

        $(document).ready(function () {
            // 定义域名变量
            var domain;
            // 判断当前环境
            if (window.location.href.indexOf('localhost') !== -1 || window.location.href.indexOf('127.0.0.1') !== -1) {
                // 本地开发环境
                domain = "http://127.0.0.1:5500";
            } else {
                // 线上环境
                domain = "http://mainbao.gitee.io/pianosystem1";
            }

            var audioContext = new (window.AudioContext || window.webkitAudioContext)();
            var tracks = [];
            var activeDivs = [];

            // 创建音轨
            function createTrack(src) {
                var audio = new Audio(domain + "/mp3/" + src);
                var track = audioContext.createMediaElementSource(audio);
                return { audio: audio, track: track };
            }

            // 播放音轨
            function playTrack(index) {
                if (!audioMap[index]) {
                    alert(index)
                    var audioSrc = $(".audio-item").eq(index).data("src");
                    var { audio, track } = createTrack(audioSrc);
                    var merger = audioContext.createChannelMerger(2);
                    track.connect(merger);
                    merger.connect(audioContext.destination);
                    audio.play();
                    audioMap[index] = { audio: audio, playing: true }; // 记录音轨的播放状态
                    // 添加高亮效果
                    highlightDiv(index);
                }
            }

            // 停止音轨
            function stopAllTracks() {
                Object.values(audioMap).forEach(function (item) {
                    var audio = item.audio;
                    var playing = item.playing;
                    if (playing) {
                        // 等待当前音轨播放完毕后再停止
                        audio.addEventListener('ended', function () {
                            audio.pause();
                            audio.currentTime = 0;
                        }, { once: true });
                    } else {
                        audio.pause();
                        audio.currentTime = 0;
                    }
                });
                audioMap = {};
                // 移除所有高亮效果
                activeDivs.forEach(function (index) {
                    unhighlightDiv(index);
                });
                activeDivs = [];
            }

            var audioMap = {}; // 存储按键码和对应的音轨
            var activeDivs = []; // 存储当前高亮的div索引

            // 高亮div
            function highlightDiv(index) {
                $(".audio-item").eq(index).addClass("highlighted");
                activeDivs.push(index);
            }

            // 取消高亮div
            function unhighlightDiv(index) {
                $(".audio-item").eq(index).removeClass("highlighted");
                activeDivs = activeDivs.filter(item => item !== index);
            }

            // 监听键盘按下事件
            $(document).keydown(function (event) {
                var index = event.keyCode - 49; // 1对应键盘上的数字1的keyCode，以此类推
                if (index >= 0 && index <= 4) {
                    playTrack(index);
                }
            });

            // 监听键盘抬起事件
            $(document).keyup(function (event) {
                stopAllTracks();
            });
        });
    </script>

</body>

</html>